package edu.jxnu.zhangjinsong.unemploymenttracker.controller;

import edu.jxnu.zhangjinsong.unemploymenttracker.common.Response;
import edu.jxnu.zhangjinsong.unemploymenttracker.entity.Person;
import edu.jxnu.zhangjinsong.unemploymenttracker.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/persons")
@CrossOrigin(origins = "*")
public class PersonController {

    @Autowired
    private PersonService personService;

    /**
     * 获取人员列表
     */
    @GetMapping
    public Response getAllPersons() {
        try {
            List<Person> persons = personService.getAllPersons();
            return Response.success(persons);
        } catch (Exception e) {
            return Response.error(500, e.getMessage());
        }
    }

    /**
     * 根据ID获取人员详情
     */
    @GetMapping("/{id}")
    public Response getPersonById(@PathVariable String id) {
        try {
            Person person = personService.getPersonById(id);
            if (person == null) {
                throw new RuntimeException("Person not found with id: " + id);
            }
            return Response.success(person);
        } catch (Exception e) {
            return Response.error(404, e.getMessage());
        }
    }

    /**
     * 创建人员
     */
    @PostMapping
    public Response createPerson(@RequestBody Person person) {
        try {
            boolean success = personService.savePerson(person);
            if (success) {
                return Response.success(person);
            } else {
                return Response.error(500, "创建人员失败");
            }
        } catch (Exception e) {
            return Response.error(500, e.getMessage());
        }
    }

    /**
     * 更新人员信息
     */
    @PutMapping("/{id}")
    public Response updatePerson(@PathVariable String id, @RequestBody Person personDetails) {
        try {
            boolean success = personService.updatePerson(id, personDetails);
            if (success) {
                return Response.success(personDetails);
            } else {
                return Response.error(404, "更新人员失败，人员不存在");
            }
        } catch (Exception e) {
            return Response.error(404, e.getMessage());
        }
    }

    /**
     * 删除人员
     */
    @DeleteMapping("/{id}")
    public Response deletePerson(@PathVariable String id) {
        try {
            boolean success = personService.deletePerson(id);
            if (success) {
                return Response.success();
            } else {
                return Response.error(404, "删除人员失败，人员不存在");
            }
        } catch (Exception e) {
            return Response.error(404, e.getMessage());
        }
    }
}